package com.maimao.user.controller;

import cn.hutool.core.util.StrUtil;
import com.maimao.api.user.EnterpriseApi;
import com.maimao.api.user.UserApi;
import com.maimao.core.constant.RedisKeys;
import com.maimao.core.enums.RespCode;
import com.maimao.core.model.auth.AuthUser;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.RegexUtils;
import com.maimao.model.common.CommonCheckInput;
import com.maimao.model.goods.Brand;
import com.maimao.model.user.Enterprise;
import com.maimao.model.user.Shop;
import com.maimao.model.user.enums.CompanyFillTypeEnum;
import com.maimao.model.user.input.EmailInput;
import com.maimao.model.user.sys.vo.Permissions;
import com.maimao.user.client.BrandClient;
import com.maimao.user.controller.base.BaseController;
import com.maimao.user.mapper.ShopMapper;
import com.maimao.user.service.CompanyService;
import com.maimao.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2020/12/13 9:59 下午
 */
@RestController
public class CompanyController extends BaseController implements EnterpriseApi {
    @Autowired
    private CompanyService companyService;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据邮箱查询企业权限
     */
    @Override
    @GetMapping("/permissions-g/email")
    public Result<?> getCompanyPermissionByEmail(String email) {
        if (StringUtils.isEmpty(email) || !RegexUtils.checkEmail(email)) {
            return Result.fail(RespCode.NOT_VALID, "邮箱格式非法");
        }
        Permissions permissions = companyService.getPermissionsByEmail(email);
        return new Result<>(200, permissions, true, "ok");
    }

    @PostMapping("/register")
    @Override
    public Result<?> registerAndApplyShop(@RequestBody @Validated Enterprise enterprise) {
        String code = enterprise.getCode();
        Object cacheCode = redisTemplate.opsForValue().get(RedisKeys.SECURITY_OPERATION_EMAIL_CODE + enterprise.getEmail());
        if (cacheCode == null) {
            return Result.notValid("验证码已过期请重新获取");
        }
        if (!(cacheCode.toString()).equals(code)) {
            return Result.notValid("验证码错误");
        }
        if (enterprise.getFillType().equals(CompanyFillTypeEnum.LEGAL_PERSON.getCode())) {
            if (StrUtil.hasEmpty(enterprise.getIdUrlFront(), enterprise.getIdUrlBack())) {
                return Result.notValid("请上传法人身份证正面和反面照");
            }
        } else {
            if (StrUtil.hasEmpty(enterprise.getProxyUserFront(), enterprise.getProxyUserBack(), enterprise.getComission())) {
                return Result.notValid("请上传代理人身份证与委托书");
            }
        }
        Brand brand = enterprise.getBrand();
        if (brand == null || (brand.getId() == null && StrUtil.isEmpty(brand.getName()))) {
            return Result.notValid("请绑定品牌或申请自主品牌");
        }
        if (brand.getId() != null) {
            Result<String> res = brandClient.selectNameById(brand.getId());
            if (res == null || StrUtil.isEmpty(res.getData())) {
                return Result.notValid("目标品牌不存在");
            }

            //这里不应该添加是否官方条件 无论品牌是否为官方 都不应重复
            Shop shop = shopMapper.findShopBySocialAndBrandId(1, brand.getId());
            if (shop != null) {
                return Result.notValid("该品牌已被绑定，如非您本公司操作，请联系网站人员");
            }
        } else if (StrUtil.isNotEmpty(brand.getName())) {
            Result<Brand> brandRes = brandClient.selectByName(brand.getName());
            if (brandRes != null && brandRes.getData() != null) {
                Shop shop = shopMapper.findShopBySocialAndBrandId(1, brandRes.getData().getId());
                if (shop != null) {
                    return Result.notValid("该品牌已被绑定，如非您本公司操作，请联系网站人员");
                }
            }
        }
        companyService.register(enterprise);


        return Result.ok("创建成功，您的店铺正常申请中");
    }

    /**
     * 检查邮箱是否绑定过
     *
     * @param input
     * @return
     */
    @Override
    @PostMapping("/checkEmail")
    public Result<?> checkEmailBind(@RequestBody @Validated EmailInput input) {
        boolean res = companyService.checkEmail(input.getEmail());
        return Result.okData(res);
    }

    /**
     * 查询登录企业的店铺状态
     *
     * @return
     */
    @Override
    @GetMapping("/shopStatus")
    public Result<?> queryCompanyShopStatus() {
        AuthUser authUser = checkAndGetAuthUser();
        Long id = authUser.getId2Long();
        Integer shopStatus = companyService.findShopStatusById(id);
        return Result.okData(shopStatus);
    }

    /**
     * 审核企业开店资质信息
     */
    @PostMapping("/checkShop")
    @Override
    public Result<?> checkShop(@RequestBody CommonCheckInput input) {
        if (!input.getSuccess() && StrUtil.isEmpty(input.getReason())) {
            return Result.notValid("请填写驳回理由");
        }
        return companyService.checkShop(input.getId(), input.getSuccess(), input.getReason());
    }
}
